<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        body{
            text-align: center;
        }
        canvas{
            border: 1px solid gray;
        }
    </style>
</head>
<body>
    <canvas width="500" height="500"></canvas>
</body>
<script>
    var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");
    var timer = null;
    var arr = [];
    
    function rand(min,max){
        return Math.floor(Math.random()*(max-min))+min;
    }                                                                        
    function createLine(){
        for(var i=0;i<25;i++){
            for(var j=0;j<25;j++){
                ctx.beginPath();
                ctx.rect(i*20,j*20,20,20);
                ctx.strokeStyle = "gray";
                ctx.stroke();
            }
        }
    }
    createLine();
    function Snake(x,y){
        this.x = x;
        this.y = y;
        this.color = "cyan";
    }
    Snake.prototype.draw = function(){
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x,this.y,20,20);
        ctx.fill();
    }
    var bx = rand(2,23)*20;
    var by = rand(2,23)*20;
    var snake = new Snake(bx,by);
    var snake1 = new Snake(bx-20,by);
    var snake2 = new Snake(bx-40,by);
    window.onkeydown = function(event){
        var e = event || window.event;
        switch(e.keyCode){
            case 37:
                snake2.x=snake1.x;
                snake2.y=snake1.y;
                snake1.x=snake.x;
                snake1.y=snake.y;
                snake.x-=20;
                break;
            case 38:
                snake2.y=snake1.y;
                snake2.x=snake1.x;
                snake1.y=snake.y;
                snake1.x=snake.x;
                snake.y-=20;
                break;
            case 39:
                snake2.x=snake1.x;
                snake2.y=snake1.y;
                snake1.x=snake.x;
                snake1.y=snake.y;
                snake.x+=20;
                break;
            case 40:
                snake2.y=snake1.y;
                snake2.x=snake1.x;
                snake1.y=snake.y;
                snake1.x=snake.x;
                snake.y+=20;
                break;
        }
    }
    timer = setInterval(function(){
        ctx.clearRect(0,0,500,500);
        createLine();
        snake.draw();
        snake1.draw();
        snake2.draw();
    },500);
</script>
</html>












